package com.future.handler;

import cn.hutool.json.JSONUtil;
import com.future.allUtils.utils.WebUtils;
import com.future.domain.Result;
import com.future.exception.AccountDisabledException;
import com.future.exception.EmailNotRegisteredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String message;
        if (authException instanceof UsernameNotFoundException) {
            message = "账号不存在";
        } else if (authException instanceof EmailNotRegisteredException) {
            message = "邮箱未注册";
        } else if (authException.getMessage().contains("Bad credentials")) {
            message = "密码错误";
        } else if(authException instanceof AccountDisabledException){
            message = "禁用注销账号";
        } else {
            message = "用户认证失败请重新登录";
        }
        String json = JSONUtil.toJsonStr(Result.fail(message));
        //处理异常
        WebUtils.renderString(response, json);
    }
}
